package com.example.permissionservice.controller;

import com.example.permissionservice.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping("/permission")
@RequiredArgsConstructor
public class PermissionController {
    private final PermissionService permissionService;

    @PostMapping("/bind-default-role")
    public ResponseEntity<Void> bindDefaultRole(@RequestParam Long userId) {
        permissionService.bindDefaultRole(userId);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/user-role")
    public ResponseEntity<String> getUserRoleCode(@RequestParam Long userId) {
        return ResponseEntity.ok(permissionService.getUserRoleCode(userId));
    }

    @PostMapping("/upgrade-to-admin")
    public ResponseEntity<Void> upgradeToAdmin(@RequestParam Long userId, HttpServletRequest request) {
        String roleCode = (String) request.getAttribute("roleCode");
        System.out.println(roleCode);
        if (!"super_admin".equals(roleCode)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        permissionService.upgradeToAdmin(userId);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/downgrade-to-user")
    public ResponseEntity<Void> downgradeToUser(@RequestParam Long userId, HttpServletRequest request) {
        String roleCode = (String) request.getAttribute("roleCode");
        if (!"super_admin".equals(roleCode)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        permissionService.downgradeToUser(userId);
        return ResponseEntity.ok().build();
    }
}
